package com.hongdee.insurance.order.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hongdee.base.sendMsg.service.ISendMsgService;
import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.contact.entity.TCrmCarTaskHelp;
import com.hongdee.insurance.Constant;
import com.hongdee.insurance.car.entity.TInsuranceCar;
import com.hongdee.insurance.car.service.ITCrmCarWarningConfService;
import com.hongdee.insurance.car.service.ITInsuranceCarService;
import com.hongdee.insurance.company.entity.TInsuranceCompany;
import com.hongdee.insurance.company.entity.TInsuranceCompanyBill;
import com.hongdee.insurance.company.service.ITInsuranceCompanyBillService;
import com.hongdee.insurance.company.service.ITInsuranceCompanyService;
import com.hongdee.insurance.order.dao.ITInsuranceOrderDao;
import com.hongdee.insurance.order.entity.TInsuranceOrder;
import com.hongdee.insurance.order.entity.TInsuranceOrderItem;
import com.hongdee.insurance.order.service.ITInsuranceOrderService;
import com.hongdee.insurance.order.service.ITInsuranceOrderStatsticsService;
import com.hongdee.insurance.order.service.ITInsuranceOrderToCrmService;
import com.hongdee.insurance.quotation.entity.TInsuranceQuotation;
import com.hongdee.insurance.quotation.service.ITInsuranceQuotationService;
import com.hongdee.insurance.quotation.service.ITInsuranceTaskService;
import com.hongdee.insurance.quotationitem.service.ITInsuranceQuotationItemService;
import com.hongdee.insurance.task.dao.ITInsuranceTaskSeekHelpDao;
import com.hongdee.rbac.user.entity.TBcUser;
import com.hongdee.rbac.user.service.ITBcUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Mr. Xu on 2017/4/27.
 */
@Service
public class TInsuranceOrderServiceImpl implements ITInsuranceOrderService {

    @Autowired
    private ITInsuranceOrderDao itInsuranceOrderDao;
    @Autowired
    private ITInsuranceQuotationService quotationService;
    @Autowired
    private ITInsuranceCarService insuranceCarService;
    @Autowired
    private ITInsuranceCompanyService companyService;
    @Autowired
    private ITInsuranceCompanyBillService billService;
    @Autowired
    private ITInsuranceQuotationItemService insuranceQuotationItemService;
    @Autowired
    private ITCrmCarWarningConfService warningConfService;
    @Autowired
    private ITInsuranceOrderToCrmService orderToCrmService;
    @Autowired
    private ITInsuranceOrderStatsticsService orderStatsticsService;
    @Autowired
    private ITInsuranceTaskService insuranceTaskService;
    @Autowired
    private ITInsuranceTaskSeekHelpDao seekHelpDao;
    @Autowired
    private ITBcUserService userService;
    @Autowired
    private ISendMsgService iSendMsgService;

    String tabName = "T_Insurance_Order";


    /**
     * 保险出单保存
     * 1、保存保险单对应的优惠券信息，移动至正式表
     * 2、增加保险单与报价单的关联关系
     * 3、更新报价单的状态
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public void save(TInsuranceOrder data, String uid) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        this.saveInsuranceOrderData(data,uid,companyId);
    }

    /**
     * 保险客户求助信息出单
     * @param data
     * @param uid
     * @param helpId
     * @throws Exception
     */
    @Override
    public void saveSeekHelpOrder(TInsuranceOrder data, String uid,String helpId) throws Exception {
        //获得求助详细信息
        TCrmCarTaskHelp help=seekHelpDao.getTaskHelpInfo(helpId);
        if(help==null){
            throw new Exception("未找到对应的求助信息，请检查提交内容!!");
        }
        data.setInsuranceCommissionerName(help.getSeekHelpUserName());
        data=this.saveInsuranceOrderData(data,uid,help.getCompanyId());
        help.setOrderId(data.getId());
        help.setCompletionTime(DateUtils.getTimeStr());
        help.setCompletionUserId(uid);
        help.setCompletionUserName(TokenUtil.getUser(uid).get("uName"));
        help.setStatus(String.valueOf(com.hongdee.crm.Constant.SEEK_HELP.complete.ordinal()));
        this.seekHelpDao.saveOrUpdate(help);
    }

    /**
     * 保存保单信息
     * @param data
     * @param uid
     * @param companyId
     * @return
     * @throws Exception
     */
    private TInsuranceOrder saveInsuranceOrderData(TInsuranceOrder data, String uid,String companyId) throws Exception {
        data.setCreateUser(uid);
        this.checkOrderContractNo(data.getCompulsoryNum(), "jq", companyId); // 判断交强险合同号是否存在
        this.checkOrderContractNo(data.getCommercialinsuranceNum(), "sy", companyId); // 判断商业险合同号是否存在
        //保险公司详情
//        TInsuranceCompany company = this.companyService.getInfo(data.getInsuranceCompanyId());
        Map<String,Object> company=this.companyService.getInsuranceCompanyInfo(data.getInsuranceCompanyId(),
                data.getOutOrderDate(),uid,companyId);
        getTinsuranceOrderInfo(data, uid,companyId);

        //获得报价单信息
        TInsuranceQuotation quotation = quotationService.getInsuranceQuotationById(data.getQuotationId());
        //获得报价单交强险项目
        List<Map<String, Object>> jqItems = insuranceQuotationItemService.findQuotationJqItem(data.getQuotationId());
        //获得报价单商业险项目
        List<Map<String, Object>> syItems = insuranceQuotationItemService.findQuotationSyItem(data.getQuotationId());
        //检测佣金审核状态 没有启用临时佣金，则默认审核通过
        this.checkCommissionType(data, jqItems, syItems, quotation);
        //检测返现金额 是否大于折扣金额
        checkBackPrice(data, quotation, jqItems, syItems);

        checkContractNOSyAndJq(data, company, jqItems, syItems);
        Float jq = 0f;
        if (!"".equals(StringUtil.formatEmpty(quotation.getCompulsoryTotal()))) {
            jq = Float.valueOf(quotation.getCompulsoryTotal());
        }
        Float sy = 0f;
        if (!"".equals(StringUtil.formatEmpty(quotation.getCommercialinsuranceTotal()))) {
            sy = Float.valueOf(quotation.getCommercialinsuranceTotal());
        }
        //获得车辆信息
        TInsuranceCar car = insuranceCarService.getCarInfo(data.getCarId());
        setOrderData(data,quotation,sy.toString(),jq.toString(),companyId,car);



        //检测是否超出预警值
        this.checkWarning(data, car, uid);

        this.saveInsuranceOrder(data,uid);

        //保存交强险信息
        this.saveJqOrderItem(data, company, jqItems);
        //保存商业险信息
        this.saveSyOrderItem(data, company, syItems);
        // 保存车船税信息
        this.saveCcsOrderItem(data,company,jqItems);

        this.updInsuranceCarInfo(car, data,uid);
        //保单出单 查看是否有任务信息
        //如有任务信息则关闭更新任务
        this.insuranceTaskService.updateTaskInfo(car, data);
        //更新客户档案的新车属性、销售属性
//        this.moveCouponToReal(data.getQuotationId(), data.getCarId());
        //将保险数据录入到统计表中
        orderStatsticsService.addOrderToStatistics(companyId,data.getId());
        //将保单信息录入到CRM保险中
        orderToCrmService.insuranceOrderGoToCrmInsurance(companyId,data.getId());
        return data;
    }

    private void setOrderData(TInsuranceOrder data,TInsuranceQuotation quotation,
                              String sy,String jq,String companyId,TInsuranceCar car){
        data.setInsureType(quotation.getInsureType());
        data.setCommercialinsurancePrice(sy.toString());
        data.setCompulsoryPrice(jq.toString());
        data.setInsuranceCompanyId(quotation.getInsuranceCompanyId());//保险公司ID
        data.setStoreArea(quotation.getStoreArea());
        data.setStoreParea(quotation.getStoreParea());
        data.setStoreName(quotation.getStoreName());
        data.setStoreChanel(quotation.getStoreChanel());
        //检测合同号是否正常
        data.setCompanyId(companyId);
        data.setVin(quotation.getVin());
        data.setPlateNum(quotation.getPlateNum());
        data.setStoreCode(quotation.getStoreCode());
        data.setStoreAreaCode(quotation.getStoreAreaCode());
        data.setStorePareaCode(quotation.getStorePareaCode());

        data.setInsured(car.getInsured());//被保险人
        data.setContactPhone(car.getContactPhone());//联系电话
        data.setStoreChanel(quotation.getStoreChanel());
    }

    /**
     * 出单 并且出单后更新报价单状态
     * @param data
     * @throws Exception
     */
    private void saveInsuranceOrder(TInsuranceOrder data,String uid) throws Exception {
        //判断销售人员是否为ID
        String uName="";
        if(!"".equals(data.getInsuranceCommissionerId())) {
            if(data.getCreateUser().equals(data.getInsuranceCommissionerId())){
                uName=TokenUtil.getUser(uid).get("uName");
            }else {
                Map map = userService.info(data.getInsuranceCommissionerId());
                uName=StringUtil.formatEmpty(map.get("uName"));
            }
        }else{
            uName=TokenUtil.getUser(uid).get("uName");
        }
        data.setCreateUser(uid);
        data.setInsuranceCommissionerName(uName);
        this.itInsuranceOrderDao.saveOrUpdate(data);//保存保险单
        //出单后修改报价单状态
        if (data.getQuotationId() != null) {
            this.itInsuranceOrderDao.executeSQL("update T_Insurance_Quotation set status = '2' where id = ? ", data.getQuotationId());
        } else {
            throw new Exception("未对应报价单！");
        }
    }

    /**
     * 设置报价单相关信息
     * @param data
     * @param uid
     * @throws Exception
     */
    private void getTinsuranceOrderInfo(TInsuranceOrder data,String uid,String companyId) throws Exception {
        if("".equals(data.getOutOrderDate())){
            throw new Exception("请选择出单日期!!");
        }
        //根据报价单查询保险单
        TInsuranceOrder info = itInsuranceOrderDao.info(data.getQuotationId(), data.getCarId());
        if (info != null) {
            //判断状态，超出某些状态，提示异常信息
            if(!info.getBackType().equals("")) {
                if (!info.getBackType().equals("0")) {
                    throw new Exception("该保单已经确认返现，不允许在次编辑！！");
                }
            }
            data.setUpdateUser(uid);
            data.setUpdateTime(System.currentTimeMillis());
            //删除除了自己之外的其它订单 一个报价单 只能有一个

        }else{
            data.setCreateUser(uid);
            data.setReturnType(String.valueOf(Constant.INSURANCE_RETURN_TYPE.init.ordinal()));//0 默认 1 退保 2已退保
            data.setBackType(String.valueOf(Constant.INSURANCE_BACK_TYPE.init.ordinal()));//0未确认返现 1确认返现
            data.setCreateTime(Calendar.getInstance().getTimeInMillis());
        }
        data.setCompanyId(companyId);
    }

    /**
     * 判断商业险及交强险合同号是否都与默认的相同 如果相同，则认为并没有录入 商业险及交强险信息，提示用户重新修改
     * @param data
     * @param company
     * @throws Exception
     */
    private void checkContractNOSyAndJq(TInsuranceOrder data,Map<String,Object> company,List<Map<String,Object>> jqItem,
                                        List<Map<String,Object>> syItem) throws Exception {
        //获得保险公司信息
        //获得交强险项目
        if(jqItem.size()>0){
            if(data.getCompulsoryNum().equals(StringUtil.formatEmpty(company.get("contractJqNo")))){
                throw new Exception("请重新确认交强险合同编号，是否录入正确!!");
            }
            if("".equals(data.getCompulsoryNum())){
                throw new Exception("未填写交强险合同号!!");
            }
            if(data.getCompulsoryNum().equals(StringUtil.formatEmpty(company.get("contractJqNo")))){
                throw new Exception("交强险合同号填写错误,请检查后重试!!");
            }
            if(!"".equals(StringUtil.formatEmpty(StringUtil.formatEmpty(company.get("contractJqLen"))))){
                int len=Integer.valueOf(StringUtil.formatEmpty(company.get("contractJqLen")));
                if(len!=data.getCompulsoryNum().length()){
                    throw new Exception("交强险合同号长度与预设不相等，输入长度："+data.getCompulsoryNum().length()+" 预设长度为："+len);
                }
            }else{
                if(data.getCompulsoryNum().length()>32){
                    throw new Exception("交强险合同号超过32个长字符，请检查!!");
                }
            }
            if(jqItem.size()<2){
                throw new Exception("请勾选车船使用税及交强险!!");
            }
        }
        if(syItem.size()>0){
            if(data.getCommercialinsuranceNum().equals(StringUtil.formatEmpty(company.get("contractSyNo")))){
                throw new Exception("请重新确认商业险合同编号，是否录入正确!!");
            }
            if("".equals(data.getCommercialinsuranceNum())){
                throw new Exception("未填写商业险合同号!!");
            }
            if(data.getCommercialinsuranceNum().equals(StringUtil.formatEmpty(company.get("contractSyNo")))){
                throw new Exception("商业险合同号填写错误,请检查后重试!!");
            }
            if(!"".equals(StringUtil.formatEmpty(StringUtil.formatEmpty(company.get("contractSyLen"))))){
                int len=Integer.valueOf(StringUtil.formatEmpty(company.get("contractSyLen")));
                if(len!=data.getCommercialinsuranceNum().length()){
                    throw new Exception("商业险合同号长度与预设不相等，输入长度："+data.getCommercialinsuranceNum().length()+" 预设长度为："+len);
                }
            }else{
                if(data.getCommercialinsuranceNum().length()>32){
                    throw new Exception("商业险合同号超过32个长字符，请检查!!");
                }
            }
        }
    }

    //是否启用临时佣金，如有一个启用临时佣金 则佣金审核状态为待审核
    private void checkCommissionType(TInsuranceOrder data,List<Map<String,Object>> jqItems,
                                     List<Map<String,Object>> syItems,TInsuranceQuotation quotation) throws Exception {
        //默认为待审核
//        data.setCommissionType("0");
        if(jqItems.size()>0 && "false".equals(data.getIsCommissionJqTemp())){
            if("".equals(data.getCommissionJq())){
                throw new Exception("未设置交强险协议费率，请启用交强险临时佣金费率!!");
            }
        }
        if(jqItems.size()>0 && "true".equals(data.getIsCommissionJqTemp())){
//            data.setCommissionType("0");
            String commJqTemp=data.getCommissionJqTemp();
            if(!"".equals(commJqTemp)){
                Float jqtempF=Float.valueOf(commJqTemp);
                if(jqtempF==0){
                    throw new Exception("交强险临时佣金费率至少要大于等于0!!");
                }

            }else{
                throw new Exception("已启用交强验临时佣金，请填写临时佣金费率!!");
            }
        }

        if(jqItems.size()==0 && "true".equals(data.getIsCommissionJqTemp())){
//            data.setCommissionType("1");
        }
        if(syItems.size()>0 && "false".equals(data.getIsCommissionSyTemp())){
            if("".equals(data.getCommissionSy())){
                throw new Exception("未设置商业险协议费率，请启用商业险临时佣金费率!!");
            }
        }
        if(syItems.size()>0 && "true".equals(data.getIsCommissionSyTemp())){
//            data.setCommissionType("0");
            String commSyTemp=data.getCommissionSyTemp();
            if(!"".equals(commSyTemp)){
                Float sytempF=Float.valueOf(commSyTemp);
                if(sytempF==0){
                    throw new Exception("商业险临时佣金费率至少要大于等于0!!");
                }
            }else{
                throw new Exception("已启用商业临时佣金，请填写临时佣金费率!!");
            }
        }
        if(syItems.size()==0 && "true".equals(data.getIsCommissionSyTemp())){
//            data.setCommissionType("1");
        }
        if(syItems.size()>0 && jqItems.size()>0){
            data.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.all.ordinal()));
        }
        if(jqItems.size()>0 && syItems.size()==0){
            data.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()));
        }
        if(syItems.size()>0 && jqItems.size()==0){
            data.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()));
        }
        //皆为false 则认为没有一个启用临时佣金 可设置为审核通过
//        if("false".equals(data.getIsCommissionJqTemp()) && "false".equals(data.getIsCommissionSyTemp())){
//            data.setCommissionType("1");
//        }
//        //都为0 也可以认为淌有启用临时佣金 可设置为审核通过
//        if("0".equals(data.getIsCommissionJqTemp()) && "0".equals(data.getIsCommissionSyTemp())){
//            data.setCommissionType("1");
//        }
        data.setCommissionType("-1");
    }

    /**
     * 检测返现金额是否大于佣金折扣金额
     * @param order
     * @param quotation
     * @param jqItems
     * @param syItems
     * @throws Exception
     */
    private void checkBackPrice(TInsuranceOrder order,TInsuranceQuotation quotation,List<Map<String,Object>> jqItems,
                                List<Map<String,Object>> syItems) throws Exception {
        Float commissionPrice=0f;
        Float backPrice = Float.valueOf(order.getBackPrice());
        BigDecimal bigDecimal=new BigDecimal(order.getBackPrice());
        List<String> tpList=new ArrayList<>();
        if("".equals(order.getBackPrice())){
            order.setBackPrice("0");
        }
        if(jqItems.size()>0) {
            tpList.add("交强险折扣金额");
            Float vvt=this.getJqVVT(jqItems);
            //判断交强险是否启用临时佣金
            if ("true".equals(order.getIsCommissionJqTemp())) {
                commissionPrice += (Float.valueOf(quotation.getCompulsoryTotal())-vvt) * (Float.valueOf(order.getCommissionJqTemp()) / 100);
            } else {
                commissionPrice += (Float.valueOf(quotation.getCompulsoryTotal())-vvt) * (Float.valueOf(order.getCommissionJq()) / 100);
            }
        }

        if(syItems.size()>0) {
            tpList.add("商业险折扣金额");
            if ("true".equals(order.getIsCommissionSyTemp())) {
                commissionPrice += Float.valueOf(quotation.getCommercialinsuranceTotal()) * (Float.valueOf(order.getCommissionSyTemp()) / 100);
            } else {
                commissionPrice += Float.valueOf(quotation.getCommercialinsuranceTotal()) * (Float.valueOf(order.getCommissionSy()) / 100);
            }
            if(!"".equals(StringUtil.formatEmpty(order.getAddCommission()))){
                tpList.add("店端商业加投折扣金额");
                commissionPrice+=Float.valueOf(quotation.getCommercialinsuranceTotal())*(Float.valueOf(order.getAddCommission()) / 100);
            }
            if(!"".equals(StringUtil.formatEmpty(order.getAddCommissionPrice()))){
                commissionPrice+=Float.valueOf(order.getAddCommissionPrice());
            }
            if(!"".equals(StringUtil.formatEmpty(order.getDiscount()))){
                tpList.add("优惠券抵扣金额");
                commissionPrice+=Float.valueOf(order.getDiscount());
            }
        }

        BigDecimal b2=new BigDecimal(commissionPrice);

        if(bigDecimal.compareTo(b2)>0){
            DecimalFormat decimalFormat=new DecimalFormat(".00");
            String commissionStr=decimalFormat.format(commissionPrice);
            throw new Exception("返现金额:"+bigDecimal.toString()+"￥ 不应大于"+tpList.toString()+":"+commissionStr+"￥");
        }
    }

    /**
     * 获取车船税
     * @param jqItems
     * @return
     */
    private float getJqVVT(List<Map<String,Object>> jqItems){
        for(Map<String,Object> map:jqItems){
            String itemid=StringUtil.formatEmpty(map.get("itemId"));
            if("0".equals(itemid)){
                return Float.valueOf(StringUtil.formatEmpty(map.get("itemPrice")));
            }
        }
        return 0;
    }

    /**
     * 检测商业险保费 是否超过预警值
     * @param data
     * @param car
     * @throws Exception
     */
    private void checkWarning(TInsuranceOrder data,TInsuranceCar car,String uid) throws Exception {
        //判断商业险是否为空
        if(!"".equals(data.getCommercialinsurancePrice())) {
            data.setPriceWarningType(quotationService.checkWarningConf(data.getCommercialinsurancePrice(),uid,
                    car.getCarBrand(), car.getCarSeries(), car.getCarModel(), car.getCarConfigure()));
        }else{
            data.setPriceWarningType("1");
        }
    }
    /**
     * @Name: 保存或编辑交强险信息
     * @Author: Liu XiaoLong
     * @Date: 2017/12/29 11:16
     * @Remark:
     */
    private void saveCcsOrderItem(TInsuranceOrder order,Map<String,Object> company,List<Map<String,Object>> ccsItems) throws  Exception{
        this.itInsuranceOrderDao.delOrderItem(order.getId(), "ccs"); //删除保险单下的车船税信息
        if(ccsItems.size()>0) {
            //判断是否与默认的合同编号一致 如果一致则不允许 添加
            /*if (order.getCompulsoryNum().equals(StringUtil.formatEmpty(company.get("contractJqNo")))) {
                throw new Exception("交强险合同号填写错误,请检查后重试!!");
            }*/
            TInsuranceOrderItem item = new TInsuranceOrderItem();
            item.setBlanceType("0"); // 结算状态
            item.setCommissionId(order.getCommissionCcsId()); // 佣金费率ID =============================/???????????????????????????????????????????????
            item.setCreateTime(System.currentTimeMillis());
            item.setCreateUser(order.getCreateUser());
            item.setOrderId(order.getId()); // 保险单Id
            item.setContractType("ccs");
            item.setInsurance(order.getInsured()); // 被保险人
            item.setCompanyId(order.getCompanyId()); // 所属公司
            item.setContractNO(order.getCompulsoryNum()); // 合同号    、、车船税和交强险合同号相同
            item.setStartDate(order.getCompulsoryStartDate()); // 起始日期
            item.setStopDate(order.getCompulsoryStopDate()); // 终止日期
            item.setCommission(order.getCommissionCcs()); // 佣金费率 =====================================、？？？？？？？？？？？？？？？？？？？？？？？
            item.setCommissionTemp(order.getCommissionCcsTemp()); // 临时佣金费率 ==========================、 ？？？？？？？？？？？？？？？？？？？？？
            Float poundage = 0F;
            if("true".equals(order.getIsCommissionCcsTemp())){  // 如果启用临时费率
                poundage = Float.valueOf(order.getCommissionCcsTemp());   // 启用临时费率取临时费率
            }else{
                item.setCommissionTemp(""); // 临时佣金置空
                poundage = Float.valueOf(order.getCommissionCcs()); // 获取协议费率
            }
            //Float price = Float.valueOf(order.getCompulsoryPrice()); // 交强险成交价格


            Float vvt=getJqVVT(ccsItems); // 获取车船税
            Float price = Float.valueOf(vvt); // 赋值 车船税
            item.setPrice(price.toString());// 成交价格 .set ( 交强险成交价格 )
            DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
            item.setCommissionPrice((decimalFormat.format((price) * (poundage / 100)))); //赋值 佣金
            item.setIsCommissionTemp(order.getIsCommissionCcsTemp()); // 赋值 启用临时佣金
            item.setCommissionExp(order.getCommissionCcsExp());// 赋值 临时佣金说明
            item.setQuotationId(order.getQuotationId()); // 赋值 报价单ID
            this.itInsuranceOrderDao.saveOrUpdate(item);
        }
    }
    /**
     * 保存或编辑交强险信息
     * @param order
     * @throws Exception
     */
    private void saveJqOrderItem(TInsuranceOrder order,Map<String,Object> company,List<Map<String,Object>> jqItems) throws Exception {
        this.itInsuranceOrderDao.delOrderItem(order.getId(), "jq"); //删除保险单下的交强险信息
        if(jqItems.size()>0) {
            //判断是否与默认的合同编号一致 如果一致则不允许 添加
            if (order.getCompulsoryNum().equals(StringUtil.formatEmpty(company.get("contractJqNo")))) {
                throw new Exception("交强险合同号填写错误,请检查后重试!!");
            }
            TInsuranceOrderItem item = new TInsuranceOrderItem();
            item.setBlanceType("0");
            item.setCommissionId(order.getCommissionJqId());
            item.setCreateTime(System.currentTimeMillis());
            item.setCreateUser(order.getCreateUser());
            item.setOrderId(order.getId());
            item.setContractType("jq");
            item.setInsurance(order.getInsured());
            item.setCompanyId(order.getCompanyId());
            item.setContractNO(order.getCompulsoryNum());
            item.setStartDate(order.getCompulsoryStartDate());
            item.setStopDate(order.getCompulsoryStopDate());
            item.setCommission(order.getCommissionJq());
            item.setCommissionTemp(order.getCommissionJqTemp());
            Float poundage = 0F;
            if("true".equals(order.getIsCommissionJqTemp())){
                poundage = Float.valueOf(order.getCommissionJqTemp());
            }else{
                item.setCommissionTemp("");
                poundage = Float.valueOf(order.getCommissionJq());
            }
            Float price = Float.valueOf(order.getCompulsoryPrice());

            Float vvt=getJqVVT(jqItems);
            item.setPrice(order.getCompulsoryPrice());
            DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
            item.setCommissionPrice((decimalFormat.format((price-vvt) * (poundage / 100))));
            item.setIsCommissionTemp(order.getIsCommissionJqTemp());
            item.setCommissionExp(order.getCommissionJqExp());
            item.setQuotationId(order.getQuotationId());
            this.itInsuranceOrderDao.saveOrUpdate(item);
        }
    }

    /**
     * 保存或编辑商业险信息
     * @param order
     * @throws Exception
     */
    private void saveSyOrderItem(TInsuranceOrder order,Map<String,Object> company,List<Map<String,Object>> syItems) throws Exception {
        //删除保险单下的商业险信息
        this.itInsuranceOrderDao.delOrderItem(order.getId(), "sy");
        if(syItems.size()>0) {
            //判断是否与默认的合同编号一致 如果一致则不允许 添加
            if (order.getCommercialinsuranceNum().equals(StringUtil.formatEmpty(company.get("contractSyNo")))) {
                throw new Exception("商业险合同号填写错误，请调整后重试!!");
            }
            //商业险
            //根据ID 商业编号 查询是否存在 如果存在则修改，如果不存在则新增
            TInsuranceOrderItem item = new TInsuranceOrderItem();
            item.setBlanceType("0");
            item.setCommissionId(order.getCommissionSyId());
            item.setCreateTime(System.currentTimeMillis());
            item.setCreateUser(order.getCreateUser());
            item.setOrderId(order.getId());
            item.setContractType("sy");
            item.setInsurance(order.getInsured());
            item.setCompanyId(order.getCompanyId());
            item.setContractNO(order.getCommercialinsuranceNum());
            item.setStartDate(order.getCommercialinsuranceStartDate());
            item.setStopDate(order.getCommercialinsuranceStopDate());
            item.setPrice(order.getCommercialinsurancePrice());
            item.setCommission(order.getCommissionSy());
            item.setCommissionTemp(order.getCommissionSyTemp());
            Float price = Float.valueOf(order.getCommercialinsurancePrice());
            DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
            if(order.getInsuranceType().equals(String.valueOf(Constant.INSURNACE_TYPE.def.ordinal()))) {
                item.setAddCommission(order.getAddCommission());
                if(!"".equals(order.getAddCommission())){
                    item.setAddCommissionPrice(decimalFormat.format(price*(Float.valueOf(order.getAddCommission())/100)));
                }else{
                    item.setAddCommissionPrice(order.getAddCommissionPrice());
                }
            }
            Float poundage = 0F;
            if("true".equals(order.getIsCommissionSyTemp())){
                poundage = Float.valueOf(order.getCommissionSyTemp());
            }else{
                item.setCommissionTemp("");
                poundage = Float.valueOf(order.getCommissionSy());
            }
            item.setCommissionPrice((decimalFormat.format(price * (poundage / 100))));
            item.setIsCommissionTemp(order.getIsCommissionSyTemp());
            item.setCommissionExp(order.getCommissionSyExp());
            item.setQuotationId(order.getQuotationId());
            this.itInsuranceOrderDao.saveOrUpdate(item);
        }
    }

    /**
     * 更新客户档案信息
     * @param car
     * @param info
     * @throws Exception
     */
    private void updInsuranceCarInfo(TInsuranceCar car,TInsuranceOrder info,String uid) throws Exception {
        car.setCarProperty(info.getCarProperty());
        car.setSalesProperty(info.getSalesProperty());
        //判断是否为新保
//        String insuranceType=String.valueOf(Constant.INSURE_TYPE.sb);
//        if(info.getInsureType().equals(insuranceType)){
//            String sbSql="update t_crm_car set saler=? where  vin=? and company_id=?;";
//            String uName="";
//            if(info.getInsuranceCommissionerName().equals("")){
//                uName=TokenUtil.getUser(uid).get("uName");
//            }else{
//                uName=info.getInsuranceCommissionerName();
//            }
//            car.setSaler(uName);
//            this.itInsuranceOrderDao.executeSQL(sbSql,uName,car.getVin(),car.getCompanyId());
//        }else{
//            //更新
//            String sbSql="update t_insurance_car c1,t_crm_car c2 set c1.saler=c2.saler where " +
//                    " c1.vin=? and c1.company_id=? and c1.vin=c2.vin and c1.company_id=c2.company_id";
//            this.itInsuranceOrderDao.executeSQL(sbSql,car.getVin(),car.getCompanyId());
//        }
        this.itInsuranceOrderDao.saveOrUpdate(car);
    }

    /**
     * 移动优惠券至正式优惠券表
     * @param qId
     * @param carId
     * @throws Exception
     */
    private void moveCouponToReal(String qId,String carId) throws Exception {
        StringBuffer sql=new StringBuffer();
        sql.append( "INSERT INTO t_crm_car_coupon (id, create_time, create_user, update_time,  " +
                " update_user, activity_id, caozuo_name, chanzhi, combo_id, company_id, contact_name,  " +
                " contact_phone, create_date, dayin_date, dayin_name, gongdan_id, match_amount, match_order_num, " +
                " num, plate_num, remart, status, use_date, use_remark, usercar_id, vin, youxiaoqi,approval_status,dept_name,dept_id) ");
        sql.append("select coupon.id, coupon.create_time, coupon.create_user, coupon.update_time, coupon.update_user, coupon.activity_id, coupon.caozuo_name,  " +
                " coupon.chanzhi, coupon.combo_id, coupon.company_id, coupon.contact_name, coupon.contact_phone, coupon.create_date, coupon.dayin_date,  " +
                " coupon.dayin_name, coupon.gongdan_id, coupon.match_amount, coupon.match_order_num, coupon.num, coupon.plate_num, coupon.remart, coupon.status,  " +
                " coupon.use_date, coupon.use_remark, coupon.usercar_id, coupon.vin, coupon.youxiaoqi,coupon.approval_status," +
                " coupon.dept_name,coupon.dept_id from t_insurance_order_coupon coupon " +
                " where coupon.quotation_id=? and coupon.usercar_id=? and not EXISTS (select * from t_crm_car_coupon where coupon.id=id )");
        this.itInsuranceOrderDao.executeSQL(sql.toString(),qId,carId);

    }

    /**
     * 保险单分页查询
     *
     * @param uid
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public Map page(String uid, String start, String limit, Map data,boolean page) throws Exception {
        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        this.queryOrderInfo(sql,params,data,uid);
        Map pageMap=this.itInsuranceOrderDao.page(sql.toString(), params.toArray(), start, limit);
        if(!page) {
            List<Map<String, Object>> dataList = (List) pageMap.get("dataList");
            //遍历结果 对结果的交强险项目 商业险项目进行查询
            this.setInsuranceItemList(dataList);
            pageMap.put("dataList", dataList);
        }
        return pageMap;
    }

    private void setInsuranceItemList(List<Map<String, Object>> dataList) throws Exception {
        for(Map map:dataList){
            //取出报价单ID
            String quotationId=StringUtil.formatEmpty(map.get("quotationId"));
            if(!"".equals(quotationId)){
                //查询保险项目
                StringBuffer syItemstr=new StringBuffer();
                StringBuffer jqItemstr=new StringBuffer();
                List<Map<String,Object>> itemsList=this.getInsuranceItemList(quotationId);
                for(Map itemMap: itemsList){
                    if("0".equals(StringUtil.formatEmpty(itemMap.get("type")))){
                        //交强险
                        jqItemstr.append(StringUtil.formatEmpty(itemMap.get("itemName"))+" ");
                        if(!"".equals(StringUtil.formatEmpty(itemMap.get("itemLimit")))){
                            jqItemstr.append(" 保额:"+StringUtil.formatEmpty(itemMap.get("itemLimit")));
                        }
                        jqItemstr.append(" 保费:"+StringUtil.formatEmpty(itemMap.get("itemPrice")));
                        jqItemstr.append(";");
                    }else{
                        //商业险
                        syItemstr.append(StringUtil.formatEmpty(itemMap.get("itemName"))+" ");
                        if(!"".equals(StringUtil.formatEmpty(itemMap.get("itemLimit")))){
                            syItemstr.append(" 保额:"+StringUtil.formatEmpty(itemMap.get("itemLimit")));
                        }
                        syItemstr.append(" 保费:"+StringUtil.formatEmpty(itemMap.get("itemPrice")));
                        syItemstr.append(";");
                    }
                }
                map.put("syItems",syItemstr.toString());
                map.put("jqItems",jqItemstr.toString());

            }
        }
    }

    private List<Map<String,Object>> getInsuranceItemList(String quotationId) throws Exception {
        String sql="select item_name,item_price,type,item_limit from t_insurance_quotation_item where quotation_id=?";
        return this.itInsuranceOrderDao.list(sql,quotationId);
    }

    /**
     * 查询sql
     * @param sql
     * @param params
     * @param data
     * @param uid
     */
    private void queryOrderInfo(StringBuffer sql,List params,Map data,String uid){

        sql.append("select tio.*,tc.plate_num,tc.vin,tic.insurance_company_name, " +
                "sy.start_date syStartDate,sy.stop_date syStopDate,sy.contract_no syContractNo,sy.price syPrice," +
                "sy.syCommission,sy.commission_price syCommissionPrice,sy.add_commission syAddCommission," +
                "ROUND(sy.add_commission_price,2) syAddCommissionPrice, " +
                "jq.start_date jqStartDate,jq.stop_date jqStopDate,jq.contract_no jqContractNo,jq.price jqPrice, " +
                "jq.jqCommission,jq.commission_price jqCommissionPrice, " +
                "ROUND(jq.add_commission_price,2) jqAddCommissionPrice " +
                "from " + tabName)
                .append(" tio left join t_insurance_car tc on tio.car_id= tc.id ")
                .append(" left join (select id, blance_date, blance_type, commission, commission_exp, commission_id, " +
                        " commission_price, commission_temp, company_id, contract_no, contract_type, insurance, " +
                        " is_commission_temp, order_id, o.item_price price, start_date, stop_date," +
                        " case WHEN add_commission is null or add_commission='' then '0'  else add_commission end add_commission," +
                        " CASE is_commission_temp WHEN 'true' THEN commission_temp ELSE commission END jqCommission, " +
                        " add_commission_price from t_insurance_order_item i," +
                        " (select quotation_id,item_price item_price,item_id from t_insurance_quotation_item where item_id ='1') o " +
                        " where contract_type='jq' and i.quotation_id=o.quotation_id) as jq on tio.id=jq.order_id " +
                        " left join (select id, blance_date, blance_type, commission, commission_exp, commission_id, " +
                        " commission_price, commission_temp, company_id, contract_no, contract_type, insurance, " +
                        " is_commission_temp, order_id, price, start_date, stop_date," +
                        " case WHEN add_commission is null or add_commission='' then '0'  else add_commission end add_commission," +
                        " CASE is_commission_temp WHEN 'true' THEN commission_temp ELSE commission END syCommission, " +
                        " add_commission_price from t_insurance_order_item where contract_type='sy') as sy on tio.id=sy.order_id ")
                .append(" left join t_insurance_company tic on tio.insurance_company_id = tic.id ");
//                .append(" left join t_bc_user u on u.id=tio.create_user ");


        if((data.get("brand")!=null && !"".equals(StringUtil.formatEmpty(data.get("brand")))) ||
                (data.get("area")!=null && !"".equals(StringUtil.formatEmpty(data.get("area"))))){
            sql.append(" left JOIN t_bc_organ o ON tio.company_id=o.id ");
        }
        sql.append(" where 1=1 ");
//        if(!"".equals(StringUtil.formatEmpty(data.get("companyId")))){
        sql.append(" and tio.company_id=? ");
        params.add(TokenUtil.getCompanyId(uid));
//        }else {
//            Constant.setQueryByRoleDate(uid, sql, params, "tio");
//        }
        //筛选保险公司名称
        if (data.get("insuranceCompanyId") != null && !"".equals(StringUtil.formatEmpty(data.get("insuranceCompanyId")))) {
            sql.append(" and tic.id =? ");
            params.add(data.get("insuranceCompanyId"));
        }
        //车牌号或VIN
        if (data.get("plateNum") != null && !"".equals(StringUtil.formatEmpty(data.get("plateNum")))) {
//            sql.append(" and ( tc.plate_num like ? or tc.vin like ? ) ");
//            params.add("%" + data.get("plateNum") + "%");
//            params.add("%" + data.get("plateNum") + "%");
            if("plateNum".equals(StringUtil.formatEmpty(data.get("paramsKey")))){
                sql.append(" and ( tc.plate_num like ? ) ");
                params.add("%" + data.get("plateNum") + "%");
            }
            if("vin".equals(StringUtil.formatEmpty(data.get("paramsKey")))){
                sql.append(" and ( tc.vin like ? ) ");
                params.add("%" + data.get("plateNum") + "%");
            }
            if("contractNo".equals(StringUtil.formatEmpty(data.get("paramsKey")))){
                sql.append(" and (sy.contract_no like ? or jq.contract_no like ?) ");
                params.add("%" + data.get("plateNum") + "%");
                params.add("%" + data.get("plateNum") + "%");
            }
        }

        //出单日期
        if (data.get("outOrderStartDate") != null && !"".equals(StringUtil.formatEmpty(data.get("outOrderStartDate")))) {
            sql.append(" and tio.out_order_date >= ?  ");
            params.add(data.get("outOrderStartDate"));
        }
        if (data.get("outOrderStopDate") != null && !"".equals(StringUtil.formatEmpty(data.get("outOrderStopDate")))) {
            sql.append(" and tio.out_order_date <= ?  ");
            params.add(data.get("outOrderStopDate"));
        }
        //保险专员
        if (data.get("insuranceCommissionerName") != null && !"".equals(StringUtil.formatEmpty(data.get("insuranceCommissionerName")))) {
            sql.append(" and (tio.insurance_commissioner_name like ?) ");
            params.add("%" + StringUtil.formatEmpty(data.get("insuranceCommissionerName")) + "%");
//            params.add("%" + StringUtil.formatEmpty(data.get("insuranceCommissionerName")) + "%");
        }
        //基盘类型
        if (data.get("baseType") != null && !"".equals(StringUtil.formatEmpty(data.get("baseType")))) {
            sql.append(" and tio.base_type = ?  ");
            params.add(data.get("baseType"));
        }
        //返现状态
        if (data.get("backType") != null && !"".equals(StringUtil.formatEmpty(data.get("backType")))) {
            sql.append(" and tio.back_type = ?  ");
            params.add(data.get("backType"));
        }
        //车辆ID
        if(data.get("carId")!=null && !"".equals(StringUtil.formatEmpty(data.get("carId")))){
            sql.append(" and tio.car_id=? ");
            params.add(StringUtil.formatEmpty(data.get("carId")));
        }
        //报价单ID
        if(data.get("quotationId")!=null && !"".equals(StringUtil.formatEmpty(data.get("quotationId")))){
            sql.append(" and tio.quotation_id=? ");
            params.add(StringUtil.formatEmpty(data.get("quotationId")));
        }
        if(data.get("commissionType")!=null && !"".equals(StringUtil.formatEmpty(data.get("commissionType")))){
            sql.append(" and tio.commission_type=? ");
            params.add(StringUtil.formatEmpty(data.get("commissionType")));
        }
        //投保类别
        if(data.get("insureType")!=null && !"".endsWith(StringUtil.formatEmpty(data.get("insureType")))){
            sql.append(" and tio.insure_type=? ");
            params.add(StringUtil.formatEmpty(data.get("insureType")));
        }
        if(data.get("brand")!=null && !"".equals(StringUtil.formatEmpty(data.get("brand")))){
            sql.append(" and o.o_car_brand=? ");
            params.add(StringUtil.formatEmpty(data.get("brand")));
        }
        if(data.get("area")!=null && !"".equals(StringUtil.formatEmpty(data.get("area")))){
            sql.append(" and o.o_area=? ");
            params.add(StringUtil.formatEmpty(data.get("area")));
        }
        //保单类别 0 正常 1 追加 2 退单
        if(data.get("insuranceType")!=null && !"".equals(StringUtil.formatEmpty(data.get("insuranceType")))){
            sql.append(" and tio.insurance_type=? ");
            params.add(StringUtil.formatEmpty(data.get("insuranceType")));
        }
        //是否单交强  0单交强 1单商业 2交强 商业
        if(data.get("iscompulsoryinsurance")!=null && !"".equals(StringUtil.formatEmpty(data.get("iscompulsoryinsurance")))){
            sql.append(" and tio.iscompulsoryinsurance=? ");
            params.add(StringUtil.formatEmpty(data.get("iscompulsoryinsurance")));
        }
        if(data.get("saler")!=null && !"".equals(StringUtil.formatEmpty(data.get("saler")))){
            sql.append(" and tc.saler like ? ");
            params.add("%"+StringUtil.formatEmpty(data.get("saler"))+"%");
        }
        sql.append(" order by tio.create_time desc ");
    }

    /**
     * 已有保险单
     *
     * @param uid
     * @param carId
     * @param start
     * @param limit
     * @return
     * @throws Exception
     */
    @Override
    public Map hasOrder(String uid, String carId, String start, String limit) throws Exception {
        List params = new ArrayList();
        params.add(carId);
        return this.itInsuranceOrderDao.page("select a.*,b.insurance_company_name from " + tabName + " a left join t_insurance_company b on a.company_id=b.id where car_id = ? ", params.toArray(), start, limit);
    }
    //---------------------------------退单代码开始----------------------------------------------------------------------
    /**
     * 保险单退回
     * @param uid
     * @param id
     * @throws Exception
     */
    @Override
    public void returnOrder(String uid, String id) throws Exception {
        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append(" update "+tabName+" set return_type = 1 ,return_date =  ?  where id = ? ");
        Date d =new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = df.format(d);
        params.add(id);
        params.add(dateNowStr);
        this.itInsuranceOrderDao.executeSQL(sql.toString(),params.toArray());
    }

    /**
     * 保险单退单
     * @param uid
     * @param data
     * @throws Exception
     */
    @Override
    public void insuranceReturnOrder(String uid,Map<String,Object> data) throws Exception {



        String companyId=TokenUtil.getCompanyId(uid);
        //保险单信息
        TInsuranceOrder insuranceOrder=JSON.toJavaObject((JSON) JSONArray.toJSON(data.get("insuranceOrder")),TInsuranceOrder.class);
        insuranceOrder.setId("");
        insuranceOrder.setQuotationId("");
        //车辆信息
        TInsuranceCar insuranceCar= insuranceCarService.getCarInfo(insuranceOrder.getCarId());
        //获取保险项目
        List<Map<String,Object>> syItems= this.getInsuranceOrderItem(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()),data);
        List<Map<String,Object>> jqItems= this.getInsuranceOrderItem(String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()),data);
        /**
         * 检测交强 商业险信息
         */
        checkSyAndJqItems(insuranceOrder,jqItems,syItems,companyId);

        //保险公司详情
//        TInsuranceCompany company=this.companyService.getInfo(insuranceOrder.getInsuranceCompanyId());
        Map<String,Object> company=this.companyService.getInsuranceCompanyInfo(insuranceOrder.getInsuranceCompanyId(),
                insuranceOrder.getOutOrderDate(),uid,companyId);
        //获得原保单
        TInsuranceOrder oldOrder=this.itInsuranceOrderDao.info(insuranceOrder.getInsuranceId());
        //获得原保险单
        TInsuranceQuotation oldQuotation=this.quotationService.getInsuranceQuotationById(oldOrder.getQuotationId());
        //检测总价 是不是大于原来的单子
        this.checkReturnOrderPrice(insuranceOrder,oldOrder,oldQuotation,uid);
        this.setupInsuranceOrder(insuranceOrder,oldQuotation,oldOrder,syItems,jqItems);
        //检测合同号
        checkContractNOSyAndJq(insuranceOrder,company,jqItems,syItems);
        //获得报价单信息
        TInsuranceQuotation quotation = this.getReturnQuotation(insuranceOrder,oldOrder,uid,insuranceCar);

        //检测佣金审核状态 没有启用临时佣金，则默认审核通过
        this.checkCommissionType(insuranceOrder,jqItems,syItems,quotation);
        //检测是否超出预警值
        this.checkWarning(insuranceOrder,insuranceCar,uid);
        //检测合同号是否正常
        insuranceOrder.setCompanyId(companyId);
        quotation.setPriceWarningType(insuranceOrder.getPriceWarningType());
        insuranceOrder.setCommercialinsuranceStopDate(quotation.getInsuranceStopDate());
        quotation.setCompulsoryTotal(String.valueOf(Float.valueOf(quotation.getCompulsoryTotal())*-1));
        quotation.setCommercialinsuranceTotal(String.valueOf(Float.valueOf(quotation.getCommercialinsuranceTotal())*-1));
        this.itInsuranceOrderDao.saveOrUpdate(quotation);
        //-----------------保存保险项目
        List<Map<String,Object>> itemList=new ArrayList<>();
        itemList.addAll(syItems);
        itemList.addAll(jqItems);
        insuranceQuotationItemService.saveOrUpdate(itemList,quotation.getId(),uid);

        insuranceOrder.setQuotationId(quotation.getId());
        //保存保单信息
        //设置为负数据
        insuranceOrder.setCommercialinsurancePrice(quotation.getCommercialinsuranceTotal());
        insuranceOrder.setCompulsoryPrice(quotation.getCompulsoryTotal());
        this.saveInsuranceOrder(insuranceOrder,uid);
        //保存商业险信息
        this.saveSyOrderItem(insuranceOrder,company,syItems);
        this.saveJqOrderItem(insuranceOrder,company,jqItems);
        //处理退单后的数据
        this.removeInsuranceOrder(oldOrder,syItems,jqItems);
        orderStatsticsService.addOrderToStatistics(TokenUtil.getCompanyId(uid),insuranceOrder.getId());
    }

    /**
     * 退单后清理保险台账信息
     * @param oldOrder
     * @param syItems
     * @param jqItems
     * @throws Exception
     */
    private void removeInsuranceOrder(TInsuranceOrder oldOrder,List<Map<String,Object>> syItems,List<Map<String,Object>> jqItems) throws Exception {
        //判断是否为交商共保
        if(oldOrder.getIscompulsoryinsurance().equals(String.valueOf(Constant.INSURANCE_PROPERTY.all.ordinal()))){
            //未退交强险
            if(syItems.size()>0){
                //判断商业险是否全退完
                List list=insuranceQuotationItemService.surplusOrderItems(oldOrder,String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()));
                if(list.size()==0){
                    //将保险台账商业险设置为空
                    this.itInsuranceOrderDao.executeSQL("update t_crm_car_insurance set commercial_company=null,commercialinsurancenum=null,contractstartinsurance=null," +
                            "contractstopinsurance=null,iscompulsoryinsurance='0' where id=?",oldOrder.getId());

                }
            }
            if(jqItems.size()>0) {
                //将保险台账交强险设置为空
                this.itInsuranceOrderDao.executeSQL("update t_crm_car_insurance set compulsory_company=null,compulsory_end_date=null,compulsoryinsurancenum=null," +
                        "compulsory_start_date=null,iscompulsoryinsurance='1' where id=?",oldOrder.getId());
            }
            List list=insuranceQuotationItemService.surplusOrderItems(oldOrder,String.valueOf(Constant.INSURANCE_PROPERTY.all.ordinal()));
            if(list.size()==0){
                //删除保险台账
                this.removeCrmInsurance(oldOrder.getId());
            }
        }
        //判断为单商业
        if(oldOrder.getIscompulsoryinsurance().equals(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()))){
            //判断商业险是否全退完
            List list=insuranceQuotationItemService.surplusOrderItems(oldOrder,String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()));
            if(list.size()==0){
                //删除保险台账
                this.removeCrmInsurance(oldOrder.getId());
            }
        }
        if(oldOrder.getIscompulsoryinsurance().equals(String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()))){
            //判断商业险是否全退完
            List list=insuranceQuotationItemService.surplusOrderItems(oldOrder,String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()));
            if(list.size()==0){
                //删除保险台账
                this.removeCrmInsurance(oldOrder.getId());
            }
        }
    }

    /**
     * 删除保险台账，同时更新保单退保状态
     * @param orderId
     * @throws Exception
     */
    private void removeCrmInsurance(String orderId) throws Exception {
        //删除保险台账
        this.itInsuranceOrderDao.executeSQL("delete from t_crm_car_insurance where id=?",orderId);
        //将保单改为已退保状态
        this.itInsuranceOrderDao.executeSQL("update t_insurance_order set return_type=2 where id=?",orderId);
        //将该保单所有的关联的追加保单 也设置为已退保状态
        this.itInsuranceOrderDao.executeSQL("update t_insurance_order set return_type=2 where insurance_id=? and insurance_type=1",orderId);
    }

    private void checkSyAndJqItems(TInsuranceOrder insuranceOrder,List<Map<String,Object>> jqItems,
                                   List<Map<String,Object>> syItems,String companyId) throws Exception {
        if(jqItems.size()==0 && syItems.size()==0){
            throw new Exception("请勾选退单项目!!");
        }
        //判断保险合同号
        if(syItems.size()>0) {
            this.checkOrderContractNo(insuranceOrder.getCommercialinsuranceNum(), "sy", companyId);
        }
        if(jqItems.size()>0) {
            this.checkOrderContractNo(insuranceOrder.getCompulsoryNum(), "jq", companyId);
            if(jqItems.size()<2){
                throw new Exception("请勾选车船使用税、交强险!!");
            }
        }
        if("true".equals(insuranceOrder.getIsCommissionJqTemp())){
            if("".equals(insuranceOrder.getCommissionJqTemp())){
                throw new Exception("启用交强临时费率，未填写交强险临时费率!!");
            }
        }else{
            if("".equals(insuranceOrder.getCommissionJq())){
                throw new Exception("未提供交强险协议费率!!");
            }
        }
        if("true".equals(insuranceOrder.getIsCommissionSyTemp())){
            if("".equals(insuranceOrder.getCommissionJqTemp())){
                throw new Exception("启用商业临时费率，未填写商业险临时费率!!");
            }
        }else{
            if("".equals(insuranceOrder.getCommissionSy())){
                throw new Exception("未提供商业险协议费率!!");
            }
        }
    }

    /**
     * 设置保单 信息
     * @param insuranceOrder
     * @param oldQuotation
     * @param oldOrder
     * @param syItems
     * @param jqItems
     */
    private void setupInsuranceOrder(TInsuranceOrder insuranceOrder,TInsuranceQuotation oldQuotation,
                 TInsuranceOrder oldOrder,List<Map<String,Object>> syItems,List<Map<String,Object>> jqItems){
        insuranceOrder.setInsureType(oldQuotation.getInsureType());
        insuranceOrder.setCarId(oldQuotation.getCarId());
        insuranceOrder.setInsuranceType(String.valueOf(Constant.INSURNACE_TYPE.back.ordinal()));
        insuranceOrder.setInsuranceCompanyId(oldQuotation.getInsuranceCompanyId());//保险公司ID
        insuranceOrder.setBackType(String.valueOf(Constant.INSURANCE_BACK_TYPE.init.ordinal()));
        //获得车辆信息
        insuranceOrder.setInsured(oldOrder.getInsured());//被保险人
        insuranceOrder.setContactPhone(oldOrder.getContactPhone());//联系电话
        if(syItems.size()>0 && jqItems.size()==0){
            insuranceOrder.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()));
        }
        if(jqItems.size()>0 && syItems.size()==0){
            insuranceOrder.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()));
        }
        if(syItems.size()>0 && jqItems.size()>0){
            insuranceOrder.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.all.ordinal()));
        }
    }

    /**
     * 获取并设置报价单信息
     * @param insuranceOrder
     * @param oldOrder
     * @param uid
     * @param insuranceCar
     * @return
     * @throws Exception
     */
    private TInsuranceQuotation getReturnQuotation(TInsuranceOrder insuranceOrder,TInsuranceOrder oldOrder,String uid,
                                                   TInsuranceCar insuranceCar) throws Exception {

        TInsuranceQuotation insuranceQuotation =null;
        insuranceQuotation=new TInsuranceQuotation();
        insuranceQuotation.setCreateTime(DateUtils.getNowTime());
        insuranceQuotation.setCreateUser(uid);
        insuranceQuotation.setCompanyId(TokenUtil.getCompanyId(uid));
        insuranceQuotation.setInsuranceCompanyId(insuranceOrder.getInsuranceCompanyId());
        insuranceQuotation.setInsuranceStartDate(insuranceOrder.getCommercialinsuranceStartDate());
        insuranceQuotation.setInsuranceStopDate(insuranceOrder.getCommercialinsuranceStopDate());
        insuranceQuotation.setContactPeople(insuranceCar.getInsured());
        insuranceQuotation.setCarId(insuranceCar.getId());
        insuranceQuotation.setCompulsoryTotal("0");
        insuranceQuotation.setContactPhone(insuranceCar.getContactPhone());
        insuranceQuotation.setCommercialinsuranceTotal(insuranceOrder.getCommercialinsurancePrice());
        insuranceQuotation.setCompulsoryTotal(insuranceOrder.getCompulsoryPrice());
        insuranceQuotation.setInsureType(oldOrder.getInsureType());
        insuranceOrder.setInsureType(oldOrder.getInsureType());
        insuranceOrder.setBaseType(oldOrder.getBaseType());
        return insuranceQuotation;
    }

    /**
     * 查找商业、交强保险项目
     * @param type
     * @param data
     * @return
     */
    private List<Map<String,Object>> getInsuranceOrderItem(String type,Map<String,Object> data) {
        List<Map<String, Object>> items = (List<Map<String, Object>>) data.get("quotationItems");
        List<Map<String, Object>> itemList = new ArrayList<>();
        for (Map<String, Object> item : items) {
            int it = Integer.valueOf(String.valueOf(item.get("id")));
            if (type.equals(String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()))) {
                if (it < 2) {
                    itemList.add(item);
                }
            }
            if (type.equals(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()))) {
                if (it > 1) {
                    itemList.add(item);
                }
            }
        }

        return itemList;
    }

    private void checkReturnOrderPrice(TInsuranceOrder newOrder,TInsuranceOrder oldOrder,TInsuranceQuotation oldQuotation,
                                       String uid) throws Exception {
        Float newSyPrice=Float.valueOf(newOrder.getCommercialinsurancePrice());
        Float newJqPrice=Float.valueOf(newOrder.getCompulsoryPrice());

        Float newAllPrice=Constant.formatFloat(newJqPrice+newSyPrice);

        Float oldAllPrice=insuranceQuotationItemService.quotationItemReturnSumPrice(uid,oldQuotation.getId(),oldOrder.getId());

        if(newAllPrice>oldAllPrice){
            throw new Exception("退保保费:"+newAllPrice+"￥ 不应该大于原保单未退保项目保费:"+oldAllPrice+"￥ !!");
        }
    }

    //------------------------------退单代码结束-------------------------------------------------------------------------


    /**
     * 获得保险单详情
     * @param qId
     * @param carId
     * @return
     * @throws Exception
     */
    @Override
    public Map info(String uid,String qId, String carId) throws Exception {
        StringBuffer sql=new StringBuffer();
        List params=new ArrayList();
        Map data=new HashMap();
        data.put("carId",carId);
        data.put("quotationId",qId);
        this.queryOrderInfoToSql(sql,params,data,uid);
        List jqItems=insuranceQuotationItemService.findQuotationJqItem(qId);
        List syItems=insuranceQuotationItemService.findQuotationSyItem(qId);
        Map map=this.itInsuranceOrderDao.info(sql.toString(),params.toArray());
        map.put("syItems",syItems.size());
        map.put("jqItems",jqItems.size());
        return map;
    }


    private void queryOrderInfoToSql(StringBuffer sql,List params,Map data,String uid){

        sql.append("select tio.*,tc.plate_num,tc.vin,tic.insurance_company_name, " +
                " sy.start_date commercialinsuranceStartDate,sy.stop_date commercialinsuranceStopDate,sy.contract_no commercialinsuranceNum," +
                " sy.price commercialinsurancePrice,sy.commission as commissionSy,sy.commission_temp commissionSyTemp," +
                " sy.is_commission_temp isCommissionSyTemp,sy.commission_exp commissionSyExp,sy.contract_no commercialinsuranceNum, " +
                " sy.add_commission,sy.add_commission_price," +
                " jq.start_date compulsoryStartDate,jq.stop_date compulsoryStopDate,jq.contract_no compulsoryNum,jq.price compulsoryPrice," +
                " jq.commission as commissionJq,jq.commission_temp commissionJqTemp,jq.is_commission_temp isCommissionJqTemp," +
                " jq.commission_exp commissionJqExp,jq.contract_no compulsoryNum,tc.car_property,tc.sales_property" +
                " from " + tabName)
                .append(" tio left join t_insurance_car tc on tio.car_id= tc.id ")
                .append(" left join (select * from t_insurance_order_item where contract_type='jq') as jq on tio.id=jq.order_id " +
                        " left join (select * from t_insurance_order_item where contract_type='sy') as sy on tio.id=sy.order_id ")
                .append(" left join t_insurance_company tic on tio.insurance_company_id = tic.id ")
                .append(" left join t_bc_user u on u.id=tio.create_user ");

        sql.append(" where tio.company_id=? ");
        params.add(TokenUtil.getCompanyId(uid));
        if(!"".equals(StringUtil.formatEmpty(data.get("orderId")))){
            sql.append(" and tio.id=? ");
            params.add(StringUtil.formatEmpty(data.get("orderId")));
        }
        if(data.get("carId")!=null && !"".equals(StringUtil.formatEmpty(data.get("carId")))){
            sql.append(" and tio.car_id=? ");
            params.add(StringUtil.formatEmpty(data.get("carId")));
        }
        if(data.get("quotationId")!=null && !"".equals(StringUtil.formatEmpty(data.get("quotationId")))){
            sql.append(" and tio.quotation_id=? ");
            params.add(StringUtil.formatEmpty(data.get("quotationId")));
        }
    }

    /**
     * 检测合同号是否重复
     * @param contractNo
     * @param type
     * @param companyId
     * @return
     * @throws Exception
     */
    public void checkOrderContractNo(String contractNo,String type,String companyId) throws Exception {
        String sql="select * from t_insurance_order_item where contract_no=? and contract_type=? and company_id=? ";
        List list=this.itInsuranceOrderDao.list(sql,contractNo,type,companyId);
        if(list.size()>0){
            String insuranceType="商业险";
            if("jq".equals(type)){
                insuranceType="交强险";
            }
            throw new Exception(insuranceType+" "+contractNo+" 合同号已存在，请调整后重新录入");
        }
    }

    /**
     * 返现确认
     * @param id
     * @param uid
     * @param time
     * @return
     * @throws Exception
     */
    @Override
    public TInsuranceOrder confimBack(String id,String uid,String time,String backPrice) throws Exception {
        TInsuranceOrder insuranceOrder = this.itInsuranceOrderDao.info(id);
        insuranceOrder.setBackType(String.valueOf(Constant.INSURANCE_BACK_TYPE.argee.ordinal()));
        insuranceOrder.setBackDate(time);
        insuranceOrder.setUpdateTime(System.currentTimeMillis());
        insuranceOrder.setUpdateUser(uid);
        if(!"0".equals(backPrice)) {
            insuranceOrder.setBackPrice(backPrice);

            TInsuranceOrderItem syItem=this.itInsuranceOrderDao.getOrderItemInfo(insuranceOrder.getId(),"sy");
            TInsuranceOrderItem jqItem=this.itInsuranceOrderDao.getOrderItemInfo(insuranceOrder.getId(),"jq");

            if(jqItem!=null) {
                insuranceOrder.setCommissionJqTemp(jqItem.getCommissionTemp());
                insuranceOrder.setIsCommissionJqTemp(jqItem.getIsCommissionTemp());
                insuranceOrder.setCommissionJq(jqItem.getCommission());
            }
            if(syItem!=null) {
                insuranceOrder.setCommissionSyTemp(syItem.getCommissionTemp());
                insuranceOrder.setIsCommissionSyTemp(syItem.getIsCommissionTemp());
                insuranceOrder.setCommissionSy(syItem.getCommission());
                insuranceOrder.setAddCommissionPrice(syItem.getAddCommissionPrice());
            }

            //查询原有保单信息
            TInsuranceQuotation quotation = quotationService.getInsuranceQuotationById(insuranceOrder.getQuotationId());
            //获得报价单交强险项目
            List<Map<String, Object>> jqItems = insuranceQuotationItemService.findQuotationJqItem(insuranceOrder.getQuotationId());
            //获得报价单商业险项目
            List<Map<String, Object>> syItems = insuranceQuotationItemService.findQuotationSyItem(insuranceOrder.getQuotationId());
            //检测返现金额 是否大于折扣金额
            checkBackPrice(insuranceOrder, quotation, jqItems, syItems);
        }
        this.itInsuranceOrderDao.saveOrUpdate(insuranceOrder);
        orderStatsticsService.updOrderToStatistics(insuranceOrder.getId(),insuranceOrder.getCompanyId());
        //返现成功后，给保险销售人员发送短信 1 根据保单Id查询销售人员姓名电话，客户姓名。2 调用发送短信接口，给销售人员发送短信。
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT o.insured, u.u_name, u.u_mobile,o.back_date, " +
                "o.back_Price FROM t_insurance_order o, t_bc_user u " +
                "WHERE o.id = ? " +
                "AND u.id = o.insurance_commissioner_id; ");
        List params = new ArrayList();
        params.add(id);
        Map map = this.itInsuranceOrderDao.info(sql.toString(),params.toArray());
        if(!"".equals(map.get("uMobile"))){
            //编辑短信内容
            String msg = map.get("uName")+"您好，您的客户"+ map.get("insured") +"购买的保险已经返现了,返现日期为: " +
                    map.get("backDate") + ",返现金额为:" +map.get("backPrice") + "元";
            List phone = new ArrayList();
            phone.add(map.get("uMobile"));
            this.iSendMsgService.sendGet(msg,phone,"10661234");
        }
        return insuranceOrder ;
    }

    /**
     * 保险退单
     * @param id
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public TInsuranceCar returnInsurance(String id,String uid) throws Exception {
        TInsuranceOrder insuranceOrder=this.itInsuranceOrderDao.info(id);
        insuranceOrder.setReturnType(String.valueOf(Constant.INSURANCE_RETURN_TYPE.inaudit.ordinal()));
        insuranceOrder.setReturnDate(DateUtils.getTimeStr(DateUtils.YYYYMMDD));
        insuranceOrder.setUpdateTime(System.currentTimeMillis());
        insuranceOrder.setUpdateUser(uid);
        return (TInsuranceCar) this.itInsuranceOrderDao.saveOrUpdate(insuranceOrder);
    }

    /**
     * 新增保险单
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public void addInsuranceOrder(Map data, String uid) throws Exception {
        String companyId=TokenUtil.getCompanyId(uid);

        //车辆信息
        TInsuranceCar insuranceCar= JSON.toJavaObject((JSON) JSONArray.toJSON(data.get("carInfo")),TInsuranceCar.class);
        //保险单信息
        TInsuranceOrder insuranceOrder=JSON.toJavaObject((JSON) JSONArray.toJSON(data.get("insuranceOrder")),TInsuranceOrder.class);
        this.checkOrderContractNo(insuranceOrder.getCompulsoryNum(),"jq",companyId); // 交强合同号是否存在
        this.checkOrderContractNo(insuranceOrder.getCommercialinsuranceNum(),"sy",companyId);// 商业险合同号是否存在
        insuranceOrder.setContactPhone(insuranceCar.getContactPhone());
        insuranceOrder.setCommissionType("0");
        insuranceOrder.setBackType("0");
        insuranceOrder.setReturnType("0");
        insuranceCar=insuranceCarService.saveOrUpdate(insuranceCar,uid); // 补全车辆档案

        //保险项目
        List<Map<String,Object>> quotationItems= (List<Map<String,Object>>) data.get("quotationItems");
        /**
         * 检测保险项目是否与保单类型一致
         */
        checkQuotationItems(quotationItems,insuranceOrder);
        //报价单信息
        Map quotationMap= (Map) data.get("quotationInfo");
        TInsuranceQuotation insuranceQuotation=JSON.toJavaObject((JSON) JSONArray.toJSON(quotationMap.get("paramQuotation")),TInsuranceQuotation.class);
        insuranceQuotation.setCarId(insuranceCar.getId());
        insuranceQuotation.setId(StringUtil.formatEmpty(quotationMap.get("id")));
        insuranceQuotation.setInsuranceCompanyId(insuranceOrder.getInsuranceCompanyId());
        insuranceQuotation.setInsuranceStartDate(insuranceOrder.getCommercialinsuranceStartDate());
        insuranceQuotation.setContactPeople(insuranceCar.getContactName());
        insuranceQuotation.setContactPhone(insuranceCar.getContactPhone());
        insuranceQuotation.setCompulsoryTotal(insuranceOrder.getCompulsoryPrice());
        insuranceQuotation.setCommercialinsuranceTotal(insuranceOrder.getCommercialinsurancePrice());
        insuranceQuotation.setIscompulsoryinsurance(insuranceOrder.getIscompulsoryinsurance());//设置单交强 单商业 交商互保
        insuranceQuotation=quotationService.saveOrUpdate(insuranceQuotation,uid,StringUtil.formatEmpty(quotationMap.get("insurance")));
        /**
         * 保存保险项目信息
         */
        insuranceQuotationItemService.saveOrUpdate(quotationItems,insuranceQuotation.getId(),uid); // 报价单项目保存

        insuranceOrder.setInsuranceType(String.valueOf(Constant.INSURNACE_TYPE.def.ordinal()));
        insuranceOrder.setCarId(insuranceCar.getId());
        insuranceOrder.setQuotationId(insuranceQuotation.getId());
        insuranceOrder.setInsuranceCompanyId(insuranceQuotation.getInsuranceCompanyId());

        this.save(insuranceOrder,uid);
    }

    /**
     * 检测保单类型是否与选择的保险项目一致
     * @param quotationItems
     * @param insuranceOrder
     * @throws Exception
     */
    private void checkQuotationItems(List<Map<String,Object>> quotationItems,TInsuranceOrder insuranceOrder) throws Exception {
        int syCount=0;
        int jqCount=0;
        for(Map<String,Object> map:quotationItems){
            if(Integer.valueOf(String.valueOf(map.get("id")))<2){
                jqCount++;
            }
            if(Integer.valueOf(String.valueOf(map.get("id")))>1){
                syCount++;
            }
        }

        if(String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()).equals(insuranceOrder.getIscompulsoryinsurance())){
            if(jqCount==0){
                throw new Exception("保单为单交强，请勾选交强险项目!!");
            }
            if(syCount>0){
                throw new Exception("保单为单交强，请不要勾选商业险项目!!");
            }
            if(jqCount<2){
                throw new Exception("保单为单交强，请勾选车船税使用税和交强险!!!!");
            }
        }
        if(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()).equals(insuranceOrder.getIscompulsoryinsurance())){
            if(syCount==0){
                throw new Exception("保单为单商业，请勾选商业险项目!!");
            }
            if(jqCount>0){
                throw new Exception("保单为单商业，请不要勾选交强险项目!!");
            }
        }
        if(String.valueOf(Constant.INSURANCE_PROPERTY.all.ordinal()).equals(insuranceOrder.getIscompulsoryinsurance())){
            if(jqCount==0){
                throw new Exception("保单为交商共保，请勾选交强险项目!!");
            }
            if(syCount==0){
                throw new Exception("保单为交商共保，请勾选商业险项目!!");
            }
            if(jqCount<2){
                throw new Exception("保单为交商共保，请勾选车船税使用税和交强险!!");
            }
        }
    }




    /**
     * 追加保险单
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public void insuranceOrderAppend(Map data, String uid) throws Exception {
        String companyId=TokenUtil.getCompanyId(uid);
        //保险单信息
        TInsuranceOrder insuranceOrder=JSON.toJavaObject((JSON) JSONArray.toJSON(data.get("insuranceOrder")),TInsuranceOrder.class);
        insuranceOrder.setId("");
        insuranceOrder.setQuotationId("");
        insuranceOrder.setCompulsoryNum("");
        insuranceOrder.setCompulsoryStartDate("");
        insuranceOrder.setCompulsoryStopDate("");
        insuranceOrder.setCompulsoryPrice("");
        insuranceOrder.setCommissionJq("");
        insuranceOrder.setCommissionJqExp("");
        insuranceOrder.setCommissionJqTemp("");
        insuranceOrder.setCommissionJqId("");
        //车辆信息
        TInsuranceCar insuranceCar= insuranceCarService.getCarInfo(insuranceOrder.getCarId());
        this.checkOrderContractNo(insuranceOrder.getCommercialinsuranceNum(),"sy",companyId);
        //保险公司详情
        Map<String,Object> company=this.companyService.getInsuranceCompanyInfo(insuranceOrder.getInsuranceCompanyId(),
                insuranceOrder.getOutOrderDate(),uid,companyId);
        //获得原保单信息
        TInsuranceOrder oldOrder=this.itInsuranceOrderDao.info(insuranceOrder.getInsuranceId());
        //获得原报价单信息
        TInsuranceQuotation oldQuotation=this.quotationService.getInsuranceQuotationById(oldOrder.getQuotationId());
        //获得报价单信息
        TInsuranceQuotation quotation = this.getAppendQuotation(insuranceOrder,uid,insuranceCar);
        List<Map<String,Object>> syItems= (List<Map<String, Object>>) data.get("quotationItems");
        if(syItems.size()==0){
            throw new Exception("请勾选追加的保险项目!!");
        }
        //检测保单单项目
        insuranceOrder.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()));
        checkQuotationItems(syItems,insuranceOrder);
        checkContractNOSyAndJq(insuranceOrder,company,new ArrayList<>(),syItems);
        Float sy=0f;
        if(!"".equals(StringUtil.formatEmpty(quotation.getCommercialinsuranceTotal()))){
            sy=Float.valueOf(quotation.getCommercialinsuranceTotal());
        }
        insuranceOrder.setInsureType(quotation.getInsureType());
        insuranceOrder.setCommercialinsurancePrice(sy.toString());
        insuranceOrder.setCarId(insuranceCar.getId());
        insuranceOrder.setInsuranceType(String.valueOf(Constant.INSURNACE_TYPE.add.ordinal()));
        insuranceOrder.setInsuranceCompanyId(quotation.getInsuranceCompanyId());//保险公司ID
        insuranceOrder.setBackType(String.valueOf(Constant.INSURANCE_BACK_TYPE.init.ordinal()));
        //获得车辆信息
        insuranceOrder.setInsured(insuranceCar.getInsured());//被保险人
        insuranceOrder.setContactPhone(insuranceCar.getContactPhone());//联系电话
        //检测佣金审核状态 没有启用临时佣金，则默认审核通过
        this.checkCommissionType(insuranceOrder,new ArrayList<>(),syItems,quotation);
        //检测是否超出预警值
        this.checkWarning(insuranceOrder,insuranceCar,uid);
        //检测合同号是否正常
        insuranceOrder.setCompanyId(companyId);
        quotation.setPriceWarningType(insuranceOrder.getPriceWarningType());
        insuranceOrder.setCommercialinsuranceStopDate(quotation.getInsuranceStopDate());
        this.itInsuranceOrderDao.saveOrUpdate(quotation);
        insuranceQuotationItemService.saveOrUpdate(syItems,quotation.getId(),uid);
        insuranceOrder.setQuotationId(quotation.getId());
        //保存保单信息
        this.saveInsuranceOrder(insuranceOrder,uid);
        //保存商业险信息
        this.saveSyOrderItem(insuranceOrder,company,syItems);
        //将保险数据录入到统计表中
        orderStatsticsService.addOrderToStatistics(TokenUtil.getCompanyId(uid),insuranceOrder.getId());
    }

    /**
     * 获得报价单信息
     * @param insuranceOrder
     * @param uid
     * @param insuranceCar
     * @return
     * @throws Exception
     */
    private TInsuranceQuotation getAppendQuotation(TInsuranceOrder insuranceOrder,String uid,
                                                   TInsuranceCar insuranceCar) throws Exception {

        TInsuranceQuotation insuranceQuotation =null;
        TInsuranceOrder oldOrder=this.itInsuranceOrderDao.info(insuranceOrder.getInsuranceId());
        insuranceQuotation=new TInsuranceQuotation();
        insuranceQuotation.setCreateTime(DateUtils.getNowTime());
        insuranceQuotation.setCreateUser(uid);
        insuranceQuotation.setCompanyId(TokenUtil.getCompanyId(uid));
        insuranceQuotation.setInsuranceCompanyId(insuranceOrder.getInsuranceCompanyId());
        insuranceQuotation.setInsuranceStartDate(insuranceOrder.getCommercialinsuranceStartDate());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = sdf.parse(insuranceOrder.getCommercialinsuranceStartDate());
        Long l1=DateUtils.addMonthLongTime(dt.getTime(),+12);
        Long l2=DateUtils.addDayLongTime(l1,-1);
        insuranceQuotation.setInsuranceStopDate(sdf.format(l2));
        insuranceQuotation.setContactPeople(insuranceCar.getInsured());
        insuranceQuotation.setCarId(insuranceCar.getId());
        insuranceQuotation.setCompulsoryTotal("0");
        insuranceQuotation.setContactPhone(insuranceCar.getContactPhone());
        insuranceQuotation.setCommercialinsuranceTotal(insuranceOrder.getCommercialinsurancePrice());
        insuranceQuotation.setInsureType(oldOrder.getInsureType());
        insuranceOrder.setInsureType(oldOrder.getInsureType());
        insuranceOrder.setBaseType(oldOrder.getBaseType());
        return insuranceQuotation;
    }

    /**
     *
     * @param data
     * @param uid
     * @param companyId
     * @return
     * @throws Exception
     */
    private TInsuranceCar getInsuranceCarAndUpd(Map data,String uid,String companyId) throws Exception {
        TInsuranceCar insuranceCar= JSON.toJavaObject((JSON) JSONArray.toJSON(data.get("carInfo")),TInsuranceCar.class);
        //保险单信息
        TInsuranceOrder insuranceOrder=JSON.toJavaObject((JSON) JSONArray.toJSON(data.get("insuranceOrder")),TInsuranceOrder.class);
        this.checkOrderContractNo(insuranceOrder.getCompulsoryNum(),"jq",companyId);
        this.checkOrderContractNo(insuranceOrder.getCommercialinsuranceNum(),"sy",companyId);
        insuranceOrder.setContactPhone(insuranceCar.getContactPhone());
        insuranceOrder.setCommissionType("0");
        insuranceOrder.setBackType("0");
        insuranceOrder.setReturnType("0");
        insuranceCar=insuranceCarService.saveOrUpdate(insuranceCar,uid);
        return insuranceCar;
    }

//    /**
//     * 保存保险项目
//     * @param data
//     * @param uid
//     * @param append
//     * @throws Exception
//     */
//    private void saveInsuranceOrder(Map data,String uid,boolean append) throws Exception {
//        String companyId=TokenUtil.getCompanyId(uid);
//        //车辆信息
//        TInsuranceCar insuranceCar= getInsuranceCarAndUpd(data,uid,companyId);
//        //保险单信息
//        TInsuranceOrder insuranceOrder=JSON.toJavaObject((JSON) JSONArray.toJSON(data.get("insuranceOrder")),TInsuranceOrder.class);
//        this.checkOrderContractNo(insuranceOrder.getCompulsoryNum(),"jq",companyId);
//        this.checkOrderContractNo(insuranceOrder.getCommercialinsuranceNum(),"sy",companyId);
//        //报价单信息
//        Map quotationMap= (Map) data.get("quotationInfo");
//        TInsuranceQuotation insuranceQuotation =null;
//
//        insuranceQuotation = JSON.toJavaObject((JSON) JSONArray.toJSON(quotationMap.get("paramQuotation")), TInsuranceQuotation.class);
//        insuranceQuotation.setCarId(insuranceCar.getId());
//        insuranceQuotation.setId(StringUtil.formatEmpty(quotationMap.get("id")));
//        insuranceQuotation.setInsuranceStartDate(insuranceOrder.getCommercialinsuranceStartDate());
//        insuranceQuotation.setContactPeople(insuranceCar.getContactName());
//        insuranceQuotation.setContactPhone(insuranceCar.getContactPhone());
//        insuranceQuotation.setCompulsoryTotal(insuranceOrder.getCompulsoryPrice());
//        insuranceQuotation.setCommercialinsuranceTotal(insuranceOrder.getCommercialinsurancePrice());
//        insuranceQuotation = quotationService.saveOrUpdate(insuranceQuotation, uid, StringUtil.formatEmpty(quotationMap.get("insurance")));
//        //保险项目
//        List<Map<String,Object>> quotationItems= (List<Map<String,Object>>) data.get("quotationItems");
//        insuranceQuotationItemService.saveOrUpdate(quotationItems,insuranceQuotation.getId(),uid);
//
//        insuranceOrder.setCarId(insuranceCar.getId());
//        if(append) { //追加设置保单 类别为追加状态
//            insuranceOrder.setInsureType(String.valueOf(Constant.INSURNACE_TYPE.add.ordinal()));
//        }else{//默认为def
//            insuranceOrder.setInsureType(String.valueOf(Constant.INSURNACE_TYPE.def.ordinal()));
//        }
//        insuranceOrder.setQuotationId(insuranceQuotation.getId());
//        insuranceOrder.setInsuranceCompanyId(insuranceQuotation.getInsuranceCompanyId());
//        this.save(insuranceOrder,uid);
//    }


    /**
     * 获取保单
     * 结算对账单明细查询，增加保单
     * 根据对账单所属于的保险公司信息、4s店信息、保单号、车牌号、保费、保险类别（商业or交强）查询保单
     * 同时已结算的保单不在查询之列
     * @param data
     * @param uid
     * @param billId
     * @return
     */
    @Override
    public Map<String,Object> getBlanceInsuanceOrderList(Map data,String uid,String billId,String start,String limit) throws Exception {
        //根据对账单信息 获得所对应的保险公司信息
        TInsuranceCompanyBill bill=billService.getBillInfo(billId);
        if(bill==null){
            throw new Exception("保险对账单不存在，请查看数据是否正常！！");
        }
        StringBuffer sql=new StringBuffer();
        List<Object> params=new ArrayList<>();
        sql.append("SELECT " +
                " item.*, o.car_id, " +
                " car.plate_num, " +
                " car.vin " +
                " FROM " +
                " t_insurance_order_item item " +
                " LEFT JOIN t_insurance_order o ON item.order_id = o.id " +
                " LEFT JOIN t_insurance_car car ON o.car_id = car.id ");
        sql.append(" where o.insurance_company_id=? and item.blance_type='0' " +
                "and not EXISTS (select * from t_insurance_company_bill_balance where item_id=item.id) ");
        params.add(bill.getInsuranceCompanyId());
        //单位
        List<String> carCompanyList=new ArrayList<>();
        if(data.get("carCompany") instanceof ArrayList){//判断是多选还是单选
            carCompanyList=(List<String>) data.get("carCompany");
        }else{
            carCompanyList.add(String.valueOf(data.get("carCompany")));
        }
        if(carCompanyList.size()>1){
            sql.append(" and item.company_id in ( ");
            for(int i=0;i<carCompanyList.size();i++){
                String[] companys=carCompanyList.get(i).split(",");
                sql.append(" ? ");
                params.add(companys[0]);
                if(i<(carCompanyList.size()-1)){
                    sql.append(",");
                }
            }
            sql.append(" ) ");
        }
        //保单号
        if(!"".equals(StringUtil.formatEmpty(data.get("contractNo")))){
            sql.append(" and item.contract_no like ? ");
            params.add("%"+StringUtil.formatEmpty(data.get("contractNo"))+"%");
        }
        //车牌号
        if(!"".equals(StringUtil.formatEmpty(data.get("plateNum")))){
            sql.append(" and car.plate_num like ? ");
            params.add("%"+StringUtil.formatEmpty(data.get("plateNum"))+"%");
        }
        //保费
        if(!"".equals(StringUtil.formatEmpty(data.get("price")))){
            if(!"0".equals(StringUtil.formatEmpty(data.get("price")))) {
                sql.append(" and item.price=? ");
                params.add(StringUtil.formatEmpty(data.get("price")));
            }
        }
        //保险类别
        if(!"".equals(StringUtil.formatEmpty(data.get("contractType")))){
            sql.append(" and item.contract_type=? ");
            params.add(StringUtil.formatEmpty(data.get("contractType")));
        }
        return this.itInsuranceOrderDao.page(sql.toString(),params.toArray(),start,limit);
    }

    /**
     * 更新保单信息
     * 只更新保险项目
     * 保险合同号、返现金额
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public void update(Map data,String uid) throws Exception {
        String companyId=TokenUtil.getCompanyId(uid);
        //1、取出保险项目信息
        List<Map<String,Object>> itemList=new ArrayList<>();
        if(data.get("itemList")!=null){
            if(data.get("itemList") instanceof ArrayList){
                List<Map> items= (List<Map>) data.get("itemList");
                for(int i=0;i<items.size();i++){
                    Map info=items.get(i);
                    String start=StringUtil.formatEmpty(info.get("starts")).toLowerCase();
                    if("true".toLowerCase().equals(start)){
                        itemList.add(info);
                    }
                }
            }
        }
        //2、取出保单信息
        TInsuranceOrder insuranceOrder= null;
        if(data.get("insuranceOrder")!=null){
//            JSON js= (JSON) com.alibaba.fastjson.JSONObject.toJSON(data.get("insuranceOrder"));
//            insuranceOrder= com.alibaba.fastjson.JSONObject.toJavaObject(js,TInsuranceOrder.class);
            insuranceOrder=new TInsuranceOrder();
            Map map= (Map) data.get("insuranceOrder");
            insuranceOrder.setAddCommission(StringUtil.formatEmpty(map.get("addCommission")));
            insuranceOrder.setBackPrice(StringUtil.formatEmpty(map.get("backPrice")));
            insuranceOrder.setCarId(StringUtil.formatEmpty(map.get("carId")));
            insuranceOrder.setCommercialinsuranceNum(StringUtil.formatEmpty(map.get("commercialinsuranceNum")));
            insuranceOrder.setCommercialinsurancePrice(StringUtil.formatEmpty(map.get("commercialinsurancePrice")));
            insuranceOrder.setCommissionJq(StringUtil.formatEmpty(map.get("commissionJq")));
            insuranceOrder.setCommissionJqExp(StringUtil.formatEmpty(map.get("commissionJqExp")));
            insuranceOrder.setCommissionJqTemp(StringUtil.formatEmpty(map.get("commissionJqTemp")));
            insuranceOrder.setCommissionSy(StringUtil.formatEmpty(map.get("commissionSy")));
            insuranceOrder.setCommissionSyId(StringUtil.formatEmpty(map.get("commissionSyId")));
            insuranceOrder.setCommissionSyExp(StringUtil.formatEmpty(map.get("commissionSyExp")));
            insuranceOrder.setCommissionSyTemp(StringUtil.formatEmpty(map.get("commissionSyTemp")));
            insuranceOrder.setCommissionSyId(StringUtil.formatEmpty(map.get("commissionSyId")));
            insuranceOrder.setCommissionSyTemp(StringUtil.formatEmpty(map.get("commissionSyTemp")));
            insuranceOrder.setCompulsoryNum(StringUtil.formatEmpty(map.get("compulsoryNum")));
            insuranceOrder.setCompulsoryPrice(StringUtil.formatEmpty(map.get("compulsoryPrice")));
            insuranceOrder.setDiscount(StringUtil.formatEmpty(map.get("distcount")));
            insuranceOrder.setId(StringUtil.formatEmpty(map.get("id")));
            insuranceOrder.setInsuranceId(StringUtil.formatEmpty(map.get("insuranceId")));
            insuranceOrder.setIsCommissionJqTemp(StringUtil.formatEmpty(map.get("isCommissionJqTemp")));
            insuranceOrder.setIsCommissionSyTemp(StringUtil.formatEmpty(map.get("isCommissionSyTemp")));
            insuranceOrder.setOutOrderDate(StringUtil.formatEmpty(map.get("outOrderDate")));
            insuranceOrder.setPayNum(StringUtil.formatEmpty(map.get("payNum")));
            insuranceOrder.setPayType(StringUtil.formatEmpty(map.get("payType")));
            insuranceOrder.setQuotationId(StringUtil.formatEmpty(map.get("quotationId")));


        }else{
            throw new Exception("信息错误，请检查录入的信息！！");
        }

        TInsuranceOrder order=this.itInsuranceOrderDao.info(insuranceOrder.getId());
        //如果为审核未通过，则将状态改为审核未通过，已修改
        if(String.valueOf(Constant.COMMISSION_STATUS.pass.ordinal()).equals(order.getCommissionType())){
            insuranceOrder.setCommissionType(String.valueOf(Constant.COMMISSION_STATUS.passUpd.ordinal()));
        }else{
            insuranceOrder.setCommissionType(order.getCommissionType());
        }
        //
//        if(insuranceOrder.getDiscount().equals("")){
//            insuranceOrder.setDiscount(order.getDiscount());
//        }
        //判断保险项目是否与保单类型一致，例：保单为单交强，编辑时选择了商业险项目，系统提示不能选择商业险保险项目
        this.checkQuotationItems(itemList,order);


        //获取保险公司信息
        TInsuranceCompany company=this.companyService.getInfo(order.getInsuranceCompanyId());
        //1、获得商业险或交强险信息
        TInsuranceOrderItem syItem=this.itInsuranceOrderDao.getOrderItemInfo(insuranceOrder.getId(),"sy");
        TInsuranceOrderItem jqItem=this.itInsuranceOrderDao.getOrderItemInfo(insuranceOrder.getId(),"jq");
        //先更新保险项目信息
        //3、先更新商业险保险项目 同时 更新保单相关信息
        //判断商业险是否已经结算
        if(syItem!=null) {
            if(insuranceOrder.getCommercialinsuranceNum().equals(company.getContractJqNO())){
                throw new Exception("请检查商业险合同号是否输入正确!!");
            }
            //检测合同号是否已经存在
            boolean flag=this.itInsuranceOrderDao.checkOrderItemInfoByContractNo(insuranceOrder.getCommercialinsuranceNum(),syItem.getId());
            if(!flag){
                throw new Exception("商业险合同号已经存在,请检查是否输入是否正确!!");
            }
            syItem.setContractNO(insuranceOrder.getCommercialinsuranceNum());
            syItem.setCommission(insuranceOrder.getCommissionSy());
            syItem.setCommissionTemp(insuranceOrder.getCommissionSyTemp());
            syItem.setCommissionExp(insuranceOrder.getCommissionSyExp());
            syItem.setIsCommissionTemp(insuranceOrder.getIsCommissionSyTemp());
            syItem.setAddCommission(insuranceOrder.getAddCommission());//追加费率
            this.updateOrderItem(syItem,itemList,insuranceOrder.getCommercialinsurancePrice(),uid,"1",insuranceOrder.getQuotationId(),company);
        }
        //4、在更新交强险保险项目 同时 更新保单相关信息
        if(jqItem!=null){
            if(insuranceOrder.getCompulsoryNum().equals(company.getContractJqNO())){
                throw new Exception("请检查交强险合同号是否输入正确!!");
            }
            //检测合同号是否已经存在
            boolean flag=this.itInsuranceOrderDao.checkOrderItemInfoByContractNo(insuranceOrder.getCompulsoryNum(),jqItem.getId());
            if(!flag){
                throw new Exception("交强合同号已经存在,请检查是否输入是否正确!!");
            }
            jqItem.setContractNO(insuranceOrder.getCompulsoryNum());
            jqItem.setCommission(insuranceOrder.getCommissionJq());
            jqItem.setCommissionExp(insuranceOrder.getCommissionJqExp());
            jqItem.setCommissionTemp(insuranceOrder.getCommissionJqTemp());
            jqItem.setIsCommissionTemp(insuranceOrder.getIsCommissionJqTemp());
            this.updateOrderItem(jqItem,itemList,insuranceOrder.getCompulsoryPrice(),uid,"0",insuranceOrder.getQuotationId(),company);
        }

        //获得报价单交强险项目
        List<Map<String,Object>> jqItems=insuranceQuotationItemService.findQuotationJqItem(insuranceOrder.getQuotationId());
        //获得报价单商业险项目
        List<Map<String,Object>> syItems=insuranceQuotationItemService.findQuotationSyItem(insuranceOrder.getQuotationId());

        TInsuranceQuotation insuranceQuotation=quotationService.getInsuranceQuotationById(insuranceOrder.getQuotationId());
        //检测返现金额 是否大于折扣金额
        checkBackPrice(insuranceOrder,insuranceQuotation,jqItems,syItems);
        //检测佣金信息，处理是否为单商业  单交强
        //2、更新保单信息
        insuranceOrder=this.updateInsuranceOrder(insuranceOrder,order,uid);
        //5、更新相应报价单信息
        this.updateQuotation(insuranceOrder,uid,insuranceQuotation);
        //修改统计信息中的保单信息
        orderStatsticsService.updOrderToStatistics(insuranceOrder.getId(),companyId);
        //更新保险台账信息
        orderToCrmService.updInsuranceOrderToCrmInsurance(insuranceOrder.getId(),companyId);
    }

    /**
     * 更新保险项目信息
     * @param item
     * @param itemList
     * @param insurancePrice
     * @param uid
     * @param type
     * @param quotationId
     * @throws Exception
     */
    private void updateOrderItem(TInsuranceOrderItem item,List<Map<String,Object>> itemList,String insurancePrice,String uid,String type,
                                 String quotationId,TInsuranceCompany company) throws Exception {
        //未结算的状态下允许修改，已结算不允许修改
        if(item.getBlanceType().equals(String.valueOf(Constant.INSURANCE_BLANCE_TYPE.init.ordinal()))) {

            //先更新保险项目
            insuranceQuotationItemService.updateItem(itemList, quotationId, uid, type);
            item.setUpdateUser(uid);
            item.setUpdateTime(System.currentTimeMillis());
            Float poundage = 0F;
            if (!"".equals(StringUtil.formatEmpty(item.getCommissionTemp()))) {
                poundage = Float.valueOf(item.getCommissionTemp());
            } else {
                poundage = Float.valueOf(item.getCommission());
            }
            Float price = Float.valueOf(insurancePrice);
            DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
            item.setCommissionPrice((decimalFormat.format(price * (poundage / 100))));
            item.setPrice(insurancePrice);
            this.itInsuranceOrderDao.saveOrUpdate(item);
        }
    }

    /**
     * 更新报价单信息
     * @param insuranceOrder
     * @throws Exception
     */
    private TInsuranceOrder updateInsuranceOrder(TInsuranceOrder insuranceOrder,TInsuranceOrder oldOrder,String uid) throws Exception {

        oldOrder.setCompulsoryPrice(insuranceOrder.getCompulsoryPrice());
        oldOrder.setCompulsoryNum(insuranceOrder.getCompulsoryNum());
        oldOrder.setCommercialinsurancePrice(insuranceOrder.getCommercialinsurancePrice());
        oldOrder.setCommercialinsuranceNum(insuranceOrder.getCommercialinsuranceNum());
        oldOrder.setBackPrice(insuranceOrder.getBackPrice());
        oldOrder.setUpdateTime(System.currentTimeMillis());
        oldOrder.setUpdateUser(uid);
        oldOrder.setCommissionType(insuranceOrder.getCommissionType());
        oldOrder.setDiscount(insuranceOrder.getDiscount());
        TInsuranceCar car=insuranceCarService.getCarInfo(oldOrder.getCarId());
        this.checkWarning(oldOrder,car,uid);
        return (TInsuranceOrder) this.itInsuranceOrderDao.saveOrUpdate(oldOrder);
    }

    /**
     * 更新报价单信息
     * @param insuranceOrder
     * @param uid
     * @throws Exception
     */
    private void updateQuotation(TInsuranceOrder insuranceOrder,String uid,TInsuranceQuotation insuranceQuotation) throws Exception {

        insuranceQuotation.setCommercialinsuranceTotal(insuranceOrder.getCommercialinsurancePrice());
        insuranceQuotation.setCompulsoryTotal(insuranceOrder.getCompulsoryPrice());
        insuranceQuotation.setUpdateTime(System.currentTimeMillis());
        insuranceQuotation.setUpdateUser(uid);
        insuranceQuotation.setPriceWarningType(insuranceOrder.getPriceWarningType());
        quotationService.update(insuranceQuotation);
    }

    /**
     * 根据保险单ID 获得相应信息用于编辑
     * @param orderId
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map getInsuranceOrderToUpd(String orderId,String uid) throws Exception {
        StringBuffer sql=new StringBuffer();
        List params=new ArrayList();
        Map data=new HashMap();
        data.put("orderId",orderId);
        this.queryOrderInfoToSql(sql,params,data,uid);

        Map map=this.itInsuranceOrderDao.info(sql.toString(),params.toArray());
        if(!"".equals(StringUtil.formatEmpty(map.get("quotationId")))) {
            String quotationId = StringUtil.formatEmpty(map.get("quotationId"));
            List itemList = insuranceQuotationItemService.QuotationItemList(uid, quotationId);
            map.put("itemList", itemList);
        }
        return map;
    }

    /**
     * 保单汇总统计
     * @param data
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map orderPageStatistics(Map data,String uid) throws Exception {
        Map map=new HashMap();
        Map all=this.orderPageStatisticsToSql(uid,data,"");
        map.put("all",all);
        Map jqMap=this.orderPageStatisticsToSql(uid,data,"jq");
        jqMap.remove("syPrice");
        jqMap.remove("syCommissionPrice");
        jqMap.remove("allPrice");
        jqMap.remove("allCommissionPrice");
        map.put("jq",jqMap);
        Map syMap=this.orderPageStatisticsToSql(uid,data,"sy");
        syMap.remove("jqPrice");
        syMap.remove("jqCommissionPrice");
        syMap.remove("allPrice");
        syMap.remove("allCommissionPrice");
        map.put("sy",syMap);
        return map;
    }

    private Map orderPageStatisticsToSql(String uid,Map data,String type) throws Exception {
        StringBuffer sql=new StringBuffer();
        List<String> params=new ArrayList<>();
        sql.append("select " +
                " COUNT(tio.id) count," +
                " ROUND(ifnull(SUM(tio.sy_price*1+tio.jq_price*1),0),2) allPrice," +
                " ROUND(ifnull(SUM(tio.back_Price),0),2) backPrice," +
                " ROUND(ifnull(SUM(tio.coupon_price),0),2) couponPrice," +
                " ROUND(ifnull(SUM(tio.sy_commission_price*1+tio.jq_commission_price*1),0),2) allCommissionPrice," +
                " ROUND(ifnull(SUM(tio.sy_price),0),2) syPrice," +
                " ROUND(ifnull(SUM(tio.sy_commission_price),0),2) syCommissionPrice," +
                " ROUND(ifnull(SUM(tio.jq_price),0),2) jqPrice," +
                " ROUND(ifnull(SUM(tio.jq_commission_price),0),2) jqCommissionPrice" +
                " from t_insurance_order_statistics tio");
        sql.append(" where 1=1 ");
        Constant.setQueryByRoleDate(uid,sql,params,"tio");
        if("jq".equals(type)){
            sql.append(" and tio.sy_contract_no is null and tio.jq_contractNo is not null  ");
        }
        if("sy".equals(type)){
            sql.append(" and tio.sy_contract_no is not  null and tio.jq_contractNo is  null ");
        }
        //筛选保险公司名称
        if (data.get("insuranceCompanyId") != null && !"".equals(StringUtil.formatEmpty(data.get("insuranceCompanyId")))) {
            sql.append(" and tio.insurance_company_id =? ");
            params.add(StringUtil.formatEmpty(data.get("insuranceCompanyId")));
        }

        //车牌号或VIN
        if (data.get("plateNum") != null && !"".equals(StringUtil.formatEmpty(data.get("plateNum")))) {
            sql.append(" and ( tio.plate_num like ? or tio.vin like ? ) ");
            params.add("%" + data.get("plateNum") + "%");
            params.add("%" + data.get("plateNum") + "%");
        }
        //出单日期
        if (data.get("outOrderStartDate") != null && !"".equals(StringUtil.formatEmpty(data.get("outOrderStartDate")))) {
            sql.append(" and tio.out_order_date >= ?  ");
            params.add(StringUtil.formatEmpty(data.get("outOrderStartDate")));
        }
        if (data.get("outOrderStopDate") != null && !"".equals(StringUtil.formatEmpty(data.get("outOrderStopDate")))) {
            sql.append(" and tio.out_order_date <= ?  ");
            params.add(StringUtil.formatEmpty(data.get("outOrderStopDate")));
        }
        //保险专员
        if (data.get("insuranceCommissionerName") != null && !"".equals(StringUtil.formatEmpty(data.get("insuranceCommissionerName")))) {
            sql.append(" and (tio.insurance_commissioner_name like ? or tio.u_name like ?) ");
            params.add("%" + StringUtil.formatEmpty(data.get("insuranceCommissionerName")) + "%");
            params.add("%" + StringUtil.formatEmpty(data.get("insuranceCommissionerName")) + "%");
        }
        //基盘类型
        if (data.get("baseType") != null && !"".equals(StringUtil.formatEmpty(data.get("baseType")))) {
            sql.append(" and tio.base_type = ?  ");
            params.add(StringUtil.formatEmpty(data.get("baseType")));
        }
        //返现状态
        if (data.get("backType") != null && !"".equals(StringUtil.formatEmpty(data.get("backType")))) {
            sql.append(" and tio.back_type = ?  ");
            params.add(StringUtil.formatEmpty(data.get("backType")));
        }
        //车辆ID
        if(data.get("carId")!=null && !"".equals(StringUtil.formatEmpty(data.get("carId")))){
            sql.append(" and tio.car_id=? ");
            params.add(StringUtil.formatEmpty(data.get("carId")));
        }
        //报价单ID
        if(data.get("quotationId")!=null && !"".equals(StringUtil.formatEmpty(data.get("quotationId")))){
            sql.append(" and tio.quotation_id=? ");
            params.add(StringUtil.formatEmpty(data.get("quotationId")));
        }
        if(data.get("commissionType")!=null && !"".equals(StringUtil.formatEmpty(data.get("commissionType")))){
            sql.append(" and tio.commission_type=? ");
            params.add(StringUtil.formatEmpty(data.get("commissionType")));
        }

        //投保类别
        if(data.get("insureType")!=null && !"".endsWith(StringUtil.formatEmpty(data.get("insureType")))){
            sql.append(" and tio.insure_type=? ");
            params.add(StringUtil.formatEmpty(data.get("insureType")));
        }
        sql.append(" order by tio.create_time desc ");
        return this.itInsuranceOrderDao.info(sql.toString(),params.toArray());
    }

    @Override
    public TInsuranceOrder getInfo(String id) throws Exception {
        return this.itInsuranceOrderDao.info(id);
    }

    /**
     * 提交审核
     * @param uid
     * @param orderId
     * @throws Exception
     */
    @Override
    public void subInsuranceOrder(String uid,String orderId) throws Exception {
        TInsuranceOrder data=this.itInsuranceOrderDao.info(orderId);
        int commissionType=!"".equals(data.getCommissionType())?Integer.valueOf(data.getCommissionType()):0;
        if(commissionType<0) {
            TInsuranceOrderItem syItem=this.itInsuranceOrderDao.getOrderItemInfo(data.getId(),"sy");
            TInsuranceOrderItem jqItem=this.itInsuranceOrderDao.getOrderItemInfo(data.getId(),"jq");
            this.subInsuranceOrderType(data, syItem, jqItem);
            this.itInsuranceOrderDao.saveOrUpdate(data);
        }
    }

    /**
     * 检测状态，并进行提交审核
     * @param data
     * @param syItem
     * @param jqItem
     * @throws Exception
     */
    private void subInsuranceOrderType(TInsuranceOrder data,TInsuranceOrderItem syItem,TInsuranceOrderItem jqItem) throws Exception {
        //默认为待审核
        data.setCommissionType("1");
        if(syItem!=null){
            if(!"false".equals(syItem.getIsCommissionTemp())){
                data.setCommissionType("0");
            }
        }
        if(jqItem!=null){
            if(!"false".equals(jqItem.getIsCommissionTemp())){
                data.setCommissionType("0");
            }
        }
    }


}
